package ldh.im.fxbase.util;

import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

public class DbUtil {

    public static <R> R transaction(SqlFunction<QueryRunner, Connection, R> function) throws SQLException {
        Connection connection = DbFactory.getInstance().getConnection();
        connection.setAutoCommit(false);
        try {
            QueryRunner queryRunner = DbFactory.getInstance().buildQueryRunner();
            R r = function.apply(queryRunner, connection);
            connection.commit();
            return r;
        } catch (Exception e) {
            connection.rollback();
            System.out.println("sql error:" + e.getMessage());
            throw new SQLException(e);
        } finally {
            DbFactory.getInstance().close(connection);
        }
    }

    public static interface SqlFunction<QueryRunner, Connection, R> {

        R apply(QueryRunner queryRunner, Connection connection) throws SQLException;
    }
}
